<!--
 * @Descripttion: 
 * @Author: yang fu ren
 * @version: 
 * @Date: 2025-06-23 08:48:28
 * @LastEditors: yang fu ren
 * @LastEditTime: 2025-06-23 13:35:50
-->
<template>
<<<<<<< HEAD
  <div class="apk-upload-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>APK 文件上传</span>
        </div>
      </template>

      <el-upload
        ref="uploadRef"
        class="upload-demo"
        action="/api/apk/upload"
        :auto-upload="false"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleChange"
        :file-list="fileList"
        accept=".apk"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将APK文件拖到此处，或<em>点击选择</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">
          只能上传APK文件，且不超过100MB
        </div> -->
      </el-upload>

      <el-button
        type="primary"
        @click="submitUpload"
        :disabled="!fileList.length"
        style="margin-top: 20px"
      >
        开始上传
      </el-button>
    </el-card>

    <el-card style="margin-top: 20px">
=======
<<<<<<< HEAD
  <div class="file-upload-download">
    <el-upload
      class="upload-demo"
      ref="uploadRef"
      action="/api/File/Upload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :on-success="handleSuccess"
      :on-error="handleError"
      :file-list="fileList"
      :auto-upload="false"
      :limit="3"
      :on-exceed="handleExceed"
      multiple
    >
      <el-button slot="trigger" size="small" type="primary">选择文件</el-button>
      <el-button
        style="margin-left: 10px"
        size="small"
        type="success"
=======
  <div class="apk-upload-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>APK 文件上传</span>
        </div>
      </template>

      <el-upload
        ref="uploadRef"
        class="upload-demo"
        :auto-upload="false"
        :limit="1"
        :on-exceed="handleExceed"
        :on-change="handleChange"
        :file-list="fileList"
        accept=".apk"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将APK文件拖到此处，或<em>点击选择</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          只能上传APK文件，且不超过100MB
        </div>
      </el-upload>

      <el-button
        type="primary"
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134
        @click="submitUpload"
        :disabled="!fileList.length"
        style="margin-top: 20px;"
      >
        开始上传
      </el-button>
<<<<<<< HEAD
      <div slot="tip" class="el-upload__tip"></div>
    </el-upload>

    <el-table
      :data="uploadedFiles"
      style="width: 100%; margin-top: 20px"
      v-loading="loading"
    >
      <el-table-column prop="fileName" label="文件名" width="180" />
      <el-table-column prop="fileSize" label="大小" width="180">
        <template #default="{ row }">
          {{ formatFileSize(row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column prop="uploadTime" label="上传时间">
        <template #default="{ row }">
          {{ formatDate(row.uploadTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="mini" @click="handleDownload(row)">下载</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
=======
    </el-card>

    <el-card style="margin-top: 20px;">
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
      <template #header>
        <div class="card-header">
          <span>已上传APK列表</span>
          <el-button type="text" @click="refreshList">刷新</el-button>
        </div>
      </template>

      <el-table :data="apkList" v-loading="loading">
        <el-table-column prop="name" label="文件名" width="200" />
        <el-table-column prop="version" label="版本" width="120" />
        <el-table-column prop="package" label="包名" width="200" />
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="uploadTime" label="上传时间" width="180" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
<<<<<<< HEAD
            <el-button size="mini" type="primary" @click="downloadApk(row.id)">
              下载
            </el-button>
            <el-button size="mini" type="danger" @click="deleteApk(row.id)">
=======
            <el-button
              size="mini"
              type="primary"
              @click="downloadApk(row.id)"
            >
              下载
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="deleteApk(row.id)"
            >
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
<<<<<<< HEAD
=======
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
  </div>
</template>

<script setup lang="ts">
<<<<<<< HEAD
import { ref, onMounted } from "vue";
import type { UploadFile, UploadInstance } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

interface ApkFile {
  id: number;
  name: string;
  size: number;
  uploadTime: string;
  downloadPath: string;
  version: string;
  package: string;
}

const uploadRef = ref<UploadInstance>();
const fileList = ref<UploadFile[]>([]);
const apkList = ref<ApkFile[]>([]);
const loading = ref(false);
=======
import { ref, onMounted } from 'vue'
import type { UploadFile, UploadInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

interface ApkFile {
  id: number
  name: string
  size: number
  uploadTime: string
  downloadPath: string
  version: string
  package: string
}

const uploadRef = ref<UploadInstance>()
const fileList = ref<UploadFile[]>([])
const apkList = ref<ApkFile[]>([])
const loading = ref(false)
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134

// 创建axios实例
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 30000
})

onMounted(() => {
<<<<<<< HEAD
  fetchApkList();
=======
<<<<<<< HEAD
  fetchUploadedFiles();
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
});

const fetchApkList = async () => {
  try {
    loading.value = true;
    const response = await axios.get("/api/apk/list");
    apkList.value = response.data;
  } catch (error) {
    ElMessage.error("获取APK列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

const refreshList = () => {
  fetchApkList();
};

const handleChange = (file: UploadFile, files: UploadFile[]) => {
  fileList.value = files;
};

const handleExceed = () => {
  ElMessage.warning("每次只能上传一个APK文件");
};

const submitUpload = () => {
  uploadRef.value?.submit();
};

const downloadApk = (id: number) => {
  window.open(`/api/apk/download/${id}`, "_blank");
};
=======
  fetchApkList()
})

<<<<<<< HEAD
const deleteApk = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这个APK文件吗?", "提示", {
=======
const fetchApkList = async () => {
  try {
    loading.value = true
    const response = await api.get('/apk/list')
    apkList.value = response.data
  } catch (error) {
    handleError(error, '获取APK列表失败')
  } finally {
    loading.value = false
  }
}

const refreshList = () => {
  fetchApkList()
}

const handleChange = (file: UploadFile, files: UploadFile[]) => {
  if (file.raw?.type !== 'application/vnd.android.package-archive') {
    ElMessage.warning('请上传有效的APK文件')
    return false
  }
  fileList.value = files
}

const handleExceed = () => {
  ElMessage.warning('每次只能上传一个APK文件')
}

const submitUpload = async () => {
  if (fileList.value.length === 0) return

  const formData = new FormData()
  formData.append('file', fileList.value[0].raw!)

  try {
    const response = await api.post('/apk/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      timeout: 60000
    })
    
    ElMessage.success('上传成功')
    fileList.value = []
    fetchApkList()
  } catch (error) {
    handleError(error, '上传失败')
  }
}

const downloadApk = (id: number) => {
  window.open(`${api.defaults.baseURL}/apk/download/${id}`, '_blank')
}
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134

const deleteApk = async (id: number) => {
  try {
<<<<<<< HEAD
    await ElMessageBox.confirm("确定要删除此文件吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
      type: "warning",
    });

    await axios.delete(`/api/apk/delete/${id}`);
    ElMessage.success("删除成功");
    fetchApkList();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
      console.error(error);
<<<<<<< HEAD
=======
    } else {
      ElMessage.info("已取消删除");
=======
    await ElMessageBox.confirm('确定要删除这个APK文件吗?', '提示', {
      type: 'warning'
    })
    
    await api.delete(`/apk/delete/${id}`)
    ElMessage.success('删除成功')
    fetchApkList()
  } catch (error) {
    if (error !== 'cancel') {
<<<<<<< HEAD
      handleError(error, '删除失败')
=======
      ElMessage.error('删除失败')
      console.error(error)
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
>>>>>>> 2aeb3a9529fd7ce94647b4cd5a829eef997d521e
    }
  }
};

<<<<<<< HEAD
const formatFileSize = (bytes: number) => {
=======
<<<<<<< HEAD
const formatFileSize = (bytes: number): string => {
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
  if (bytes === 0) return "0 Bytes";
  const k = 1024;
  const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
};
<<<<<<< HEAD
=======

const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  return date.toLocaleString();
};
=======
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
<<<<<<< HEAD

const handleError = (error: any, defaultMsg: string) => {
  if (axios.isAxiosError(error)) {
    const msg = error.response?.data?.message || error.message
    ElMessage.error(`${defaultMsg}: ${msg}`)
    console.error('详细错误:', {
      request: error.config,
      response: error.response?.data
    })
  } else {
    ElMessage.error(defaultMsg)
    console.error(error)
  }
}
=======
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d
>>>>>>> 2aeb3a9529fd7ce94647b4cd5a829eef997d521e
</script>

<style scoped>
.apk-upload-container {
  padding: 20px;
}
<<<<<<< HEAD
=======
<<<<<<< HEAD
.upload-demo {
  margin-bottom: 20px;
}
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}
=======
>>>>>>> 0a309aa4a58d5715ec47d7f04df4566b06ef6134
>>>>>>> fff4ffb0d6d96c797a4b8ca4140920a50d67988d

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>